'''
1、环境搭建说明：
   1)使用正常EVB板，OpenSDK接口:test_sdk_api
2、用途：重启后压测GNSS定位语句正确性，统计压力测试fail的情况和记录
3、脚本逻辑：
    1）GNSS定位：5分钟内定位失败，整个用例结束
    2）格式检查：定位成功后，截取日志，进行常见gnss语句格式检查，包括RMC GSA VTG DTM GSV GGA
'''

import subprocess
import random
import serial
import time
import datetime
from time import sleep
import re
import sys
import os
import math

# 定义常量
AT_PORT = "COM32"
DEBUG_PORT = "COM37"
BAUDRATE = 115200
DevicesID = "c4461f4d"
#GNSS定位成功后,截取的log时间，可以自行配置，默认60s
check_log_time = 60
# 定义变量
debug_serial = None
# log文件
DEBUG_LOG = ""
ADB_LOG       = ""
#GNSS语句的句式，如果有变动，对应修改句式即可
nmea_type = ["SVINF", "GSV", "BSLOC","ENUIF","BDFRM","DRINF","DOPIF","GEOIF","STIME","GSA","VTG","DTM","RMC","GNS","GGA","BSLST"]
SVINF_Sta = ["\$SVINF,\d{2}|\d{3},\d{3},\d{1},(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?)",
             "\$SVINF,\d{2},\d{3},\d{1},(.*?),(.*?),(.*?),(.*?),(.*?)"]
BSLOC_Sta = [
    "\$BSLOC,(.*?),(.*?),31.\d{6},117.\d{6},(.*?),0.\d{6},(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?)",
    "\$BSLOC,(.*?),31.\d{8},117.\d{8},(.*?),(0|1),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?)"
    "\$BSLOC,(.*?),0,177,(.*?),31.\d{8},117.\d{8},(.*?),(.*?),0.\d{2},(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?)",
    "\$BSLOC,\d{13},31.\d{8},117.\d{8},\d{3}.\d{2},(0|1),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?)\r\n",
    "\$BSLOC,\d{13},31.\d{8},117.\d{8},\d{3}.\d{2},(0|1),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),\d{2}",
    "\$BSLOC,\d{13},31.\d{8},117.\d{8},\d{3}.\d{2},(0|1),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),\d{1}",
    "\$BSLOC,\d{13},31.\d{8},117.\d{8},\d{3}.\d{2},(0|1),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?)",
    "\$BSLOC,(.*?),31.\d{8},117.\d{8},(.*?),(0|1),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?)\r\n"]
BSLST_sta = ["\$BSLST,(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?)"]
ENUIF_Sta = ["\$ENUIF,(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?)"]
BDFRM_Sta = [
    r"\$BDFRM,(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?)",
    "\$BDFRM,(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?)"]
DRINF_Sta = ["\$DRINF,(.*?),(.*?),(.*?),(.*?)"]
DOPIF_Sta = ["\$DOPIF,(.*?),(.*?),(.*?),(.*?),(.*?),(.*?)"]
GEOIF_Sta = ["\$GEOIF,(.*?),(.*?),(.*?),(.*?),(.*?),(.*?)"]
GSV_Sta = [
    "\$G\w{1}GSV,\d{1},\d{1},(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),\d{1}\*\w{2}",
    "\$G\w{1}GSV,\d{1},\d{1},(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),\d{1}\*\w{2}",
    "\$G\w{1}GSV,\d{1},\d{1},(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),\d{1}\*\w{2}",
    "\$G\w{1}GSV,\d{1},\d{1},(.*?),(.*?),(.*?),(.*?),(.*?),\d{1}\*\w{2}",
    "\$G\w{1}GSV,\d{1},\d{1},(.*?),\d{1}\*\w{2}"]
GSA_Sta = [
    "\$G\w{1}GSA,A,3,\d{2},(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),[1-6]\*\w{2}"]
VTG_Sta = ["\$G\w{1}VTG,(.*?),T,(.*?),M,(.*?),N,(.*?),K,(A|D)\*\w{2}"]
DTM_Sta = ["\$G\w{1}DTM,\w{1}\d{2},,(.*?),\w{1},(.*?),\w{1},(.*?),\w{1}\d{2}\*\w{2}"]
RMC_Sta = [
    "\$G\w{1}RMC,\d{6}.\d{2},A,31\d{2}.\d{6},\w{1},117\d{2}.\d{6},E,\d{1}.\d{1},(.*?),\d{6},\d{1}.\d{1},W,A|D,V\*\w{2}",
    "\$G\w{1}RMC,\d{6}.\d{2},A,31\d{2}.\d{6},\w{1},117\d{2}.\d{6},E,\d{1}.\d{1},,\d{6},\d{1}.\d{1},W,A|D,V\*\w{2}",
    "\$G\w{1}RMC,\d{6}.\d{2},A,31\d{2}.\d{6},\w{1},117\d{2}.\d{6},E,\d{1}.\d{1},(.*?),\d{6},\d{1}.\d{1},W,(A|D),V\*\w{2}",
    "\$G\w{1}RMC,\d{6}.\d{2},A,30\d{2}.\d{6},\w{1},114\d{2}.\d{6},E,\d{1}.\d{1},(.*?),\d{6},\d{1}.\d{1},W,A|D,V\*\w{2}",
    "\$G\w{1}RMC,\d{6}.\d{2},A,30\d{2}.\d{6},\w{1},114\d{2}.\d{6},E,\d{1}.\d{1},,\d{6},\d{1}.\d{1},W,A|D,V\*\w{2}",
    "\$G\w{1}RMC,\d{6}.\d{2},A,30\d{2}.\d{6},\w{1},114\d{2}.\d{6},E,\d{1}.\d{1},(.*?),\d{6},\d{1}.\d{1},W,(A|D),V\*\w{2}"]
GNS_Sta = [
    "\$G\w{1}GNS,\d{6}.\d{2},30\d{2}.\d{6},\w{1},114\d{2}.\d{6},E,(.*?),[0[1-9]|[1-9][0-9]],(.*?),(.*?),(.*?),(.*?),(.*?),\w{1}\*\w{2}",#武汉经纬度
    "\$G\w{1}GNS,\d{6}.\d{2},31\d{2}.\d{6},\w{1},117\d{2}.\d{6},E,(.*?),[0[1-9]|[1-9][0-9]],(.*?),(.*?),(.*?),(.*?),(.*?),\w{1}\*\w{2}",
    "\$G\w{1}GNS,\d{6}.\d{2},31\d{2}.\d{6},\w{1},117\d{2}.\d{6},E,\*\w{2}"]
GGA_Sta = [
    "\$G\w{1}GGA,\d{6}.\d{2},31\d{2}.\d{6},N,117\d{2}.\d{6},E,([1-9]|10),[0[1-9]|1[0-2]],(.*?),(.*?),M,(.*?),M,(.*?),(0[0-9][0-9][0-9]|101[0-9]|102[0-3])\*\w{2}",#合肥经纬度
    "\$G\w{1}GGA,\d{6}.\d{2},31\d{2}.\d{6},N,117\d{2}.\d{6},E,[1-2],[0[1-9]|1[0-2]],(.*?),(.*?),M,(.*?),M,,\*\w{2}",
    "\$G\w{1}GGA,\d{6}.\d{2},30\d{2}.\d{6},N,114\d{2}.\d{6},E,([1-9]|10),[0[1-9]|1[0-2]],(.*?),(.*?),M,(.*?),M,(.*?),(0[0-9][0-9][0-9]|101[0-9]|102[0-3])\*\w{2}",#武汉经纬度
    "\$G\w{1}GGA,\d{6}.\d{2},30\d{2}.\d{6},N,114\d{2}.\d{6},E,[1-2],[0[1-9]|1[0-2]],(.*?),(.*?),M,(.*?),M,,\*\w{2}"
]
STIME_Sta = ["\$STIME,(.*?),1,(.*?),\d{4},(.*?),(.*?),(.*?),(.*?),(.*?),(.*?)"]

# check_list = {"SVINF": [SVINF_Sta], "BSLOC": [BSLOC_Sta], "BSLST": [BSLST_sta], "ENUIF": [ENUIF_Sta],
#               "BDFRM": [BDFRM_Sta], "DRINF": [DRINF_Sta],
#               "DOPIF": [DOPIF_Sta], "GEOIF": [GEOIF_Sta], "GSV": [GSV_Sta], "GSA": [GSA_Sta], "VTG": [VTG_Sta],
#               "DTM": [DTM_Sta], "RMC": [RMC_Sta],
#               "GNS": [GNS_Sta], "GGA": [GGA_Sta], "STIME": [STIME_Sta]}

check_list = {"GSV": [GSV_Sta], "GSA": [GSA_Sta], "VTG": [VTG_Sta],
              "DTM": [DTM_Sta], "RMC": [RMC_Sta],
              "GNS": [GNS_Sta], "GGA": [GGA_Sta]}

def check_port_status():
    global debug_serial
    global at_serial
    try:
        debug_serial = serial.Serial(DEBUG_PORT, BAUDRATE)
    except Exception as e:
        print("debug口连接失败，请检查端口",e)
        sys.exit()
    try:
        at_serial = serial.Serial(AT_PORT, BAUDRATE)
    except Exception as e:
        print("AT口连接失败，请检查端口",e)
        sys.exit()
def flushInput():
    debug_serial.flushInput()
def creatLogFile():
    global DEBUG_LOG
    global ADB_LOG
    global AT_LOG
    AT_LOG = "AT_LOG_{}.log".format(time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime()))
    DEBUG_LOG = "DEBUG_LOG_{}.log".format(time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime()))
    ADB_LOG = "ADB_LOG_{}.log".format(time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime()))
def at_write(command, timeout, at_port_opened, at_result,RDY=0,CPIN=0):
    at_command = command.encode("UTF-8")
    at_port_opened.write(at_command)
def at_read(serial_port,logFile=""):
        global rec_str_time
        rec_str = ''
        for i in range(3):
            time.sleep(0.1)
            lenth = serial_port.inWaiting()
            rec_str = serial_port.read(lenth)
            try:
                rec_str = re.sub('\\x1b.*?m', "", rec_str.decode("UTF-8"), 0, re.I)
                for i in rec_str.split('\n'):
                    if i == '' or i == '\r' or i == '\n' or i == '\r\n':
                        continue
                    else:
                        rec_str_time = '[{0}]   {1}\n'.format(
                            str(datetime.datetime.now()),
                            (i + '\n').replace('\r', '').replace('\n', ''))
                        if logFile != "":
                            with open(logFile, 'a') as file_object:
                                file_object.write(rec_str_time)

                return rec_str
            except:
                return ""
        return rec_str
def serial_read_login(serial_port, timeout, logFile="", readtime = 0.1):
    rec_str = ''
    for i in range(timeout):
        time.sleep(readtime)
        lenth = serial_port.inWaiting()
        rec_str = serial_port.read(lenth)
        try:
            rec_str = re.sub('\\x1b.*?m', "", rec_str.decode("UTF-8"), 0, re.I)
            #print(rec_str, '\n=======')
            # print(rec_str, '\n')
            for i in rec_str.split('\n'):
                if i == '' or i == '\r' or i == '\n' or i == '\r\n':
                    # print('################')
                    continue
                else:
                    rec_str_time = '[{0}]   {1}\n'.format(
                        str(datetime.datetime.now()),
                        (i + '\n').replace('\r', '').replace('\n', ''))
                    if logFile != "":
                        with open(logFile, 'a') as file_object:
                            file_object.write(rec_str_time)
                    # with open(logFile, 'a') as file_object:
                    #     file_object.write(
                    #         '\n[ ' + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + ' ]\n' + rec_str)
            return rec_str
        except:
            return ""

    return rec_str
# def at_read(serial_port, timeout, logFile="", readtime = 0.5):
    # rec_str = ''
    # for i in range(timeout):
        # time.sleep(readtime)
        # lenth = serial_port.inWaiting()
        # rec_str = serial_port.read(lenth)
        # try:
            # rec_str = re.sub('\\x1b.*?m', "", rec_str.decode("UTF-8"), 0, re.I)
            # for i in rec_str.split('\n'):
                # if i == '' or i == '\r' or i == '\n' or i == '\r\n':
                    # continue
                # else:
                    # rec_str_time = '[{0}]   {1}\n'.format(
                        # str(datetime.datetime.now()),
                        # (i + '\n').replace('\r', '').replace('\n', ''))
                    # if logFile != "":
                        # with open(logFile, 'a') as file_object:
                            # file_object.write(rec_str_time)
            # return rec_str
        # except:
            # return ""

    # return rec_str
def at_readline(at_port_opened):
    rec_str = at_port_opened.readline()
    # rec_str = str(rec_str, encoding="utf-8")
    return rec_str
def check_mssr():
    at_write("AT+QMSSR?\r\n", 10, at_serial, "OK")
    result = serial_read_login(at_serial, 10, AT_LOG)
    if '4' not in result:
        at_write("AT+QMSSR=4\r\n", 10, at_serial, "OK")
        serial_read_login(at_serial, 10, AT_LOG)
def loginDevice(debug_serial, debug_log):
    # global DEBUG_LOG
    # 再每次登录前按ctrl+c
    # debug_serial.write(chr(0x03).encode())
    # 确认登录失败的条件，或者，不可能失败
    t1 = time.time()
    while True:
        t2 = time.time()
        t3 = t2 - t1
        if t3 > 120:
            print(t3,t2,t1)
            print("登录失败... ... ")
            break
        # print("等待登录... ... ")
        print("[" + str(datetime.datetime.now()) + "] 等待登录... ...")
        time.sleep(1)
        at_write("\r\n", 10, debug_serial, "OK")
        time.sleep(1)
        at_write("\r\n", 10, debug_serial, "OK")
        result = serial_read_login(debug_serial, 10, debug_log)
        if "login:" in result:
            time.sleep(3)
            at_write("root\r\n", 3, debug_serial, "OK")
            write_log("账号输入成功", debug_log)
            time.sleep(5)
            for i in range(300):
                result1 = serial_read_login(debug_serial, 10, debug_log)
                print(f'---{result1}---')
                if "Password:" in result1:
                    print("[" + str(datetime.datetime.now()) + "] 输入账号... ...")
                    # at_write(".a9inycGBnnq75xQ.ytHj.\r\n", 3, debug_serial, "OK")
                    at_write("oelinux123\r\n", 10, debug_serial, "OK")
                    time.sleep(1.5)
                    write_log("输入密码", debug_log)
                    serial_read_login(debug_serial, 1, debug_log)
                    print("[" + str(datetime.datetime.now()) + "] 输入密码... ...")
                    break
                elif i == 299:
                    sys.exit()
                    # at_write("\r\n", 3, debug_serial, "OK")
                    # result = serial_read(debug_serial, 3, debug_log)
                # at_write("echo 2 >/proc/sys/kernel/printk\r\n", 3, debug_serial, "OK")
                # serial_read(debug_serial, 1, debug_log)
        elif "~ #" in result:
            write_log("登录成功", debug_log)
            print("[" + str(datetime.datetime.now()) + "] 登录成功... ...")
            time.sleep(1)
            at_read(debug_serial, DEBUG_LOG)
            # at_write("mount /dev/mmcblk0p1 /mnt/sdcard\r\n", 3, debug_serial, "OK")
            # at_read(debug_serial, DEBUG_LOG)
            time.sleep(1)
            at_write("rm -rf /usrdata/qsee.log\r\n", 3, debug_serial, "OK")
            time.sleep(30)
            at_write("\r\n", 3, debug_serial, "OK")
            at_write("rm -rf  /usrdata/qsee.log\r\n", 3, debug_serial, "OK")
            time.sleep(30)         
            at_write("\r\n", 3, debug_serial, "OK")               
            at_write("df -Th /usrdata/\r\n", 3, debug_serial, "OK")
            at_read(debug_serial, DEBUG_LOG)
            at_write("sync\r\n", 3, debug_serial, "OK")
            at_write("cat /proc/tzdbg/qsee_log > /usrdata/qsee.log &\r\n", 3, debug_serial, "OK")
            time.sleep(1)
            at_read(debug_serial, DEBUG_LOG)
            at_write("cat /proc/tzdbg/qsee_log > /usrdata/qsee.log &\r\n", 3, debug_serial, "OK")
            time.sleep(1)
            at_write("echo 2 >/proc/sys/kernel/printk\r\n", 3, debug_serial, "OK")
            at_read(debug_serial, DEBUG_LOG)
            break
            # at_write("echo 2 >/proc/sys/kernel/printk\r\n", 3, debug_serial, "OK")
            serial_read_login(debug_serial, 1, debug_log)
            break
        elif 'Login incorrect' in result:
            write_log("登录密码不对，重新登录", debug_log)
            print("[" + str(datetime.datetime.now()) + "] 登录密码不对，重新登录... ...")
            # at_write("echo 2 >/proc/sys/kernel/printk\r\n", 3, debug_serial, "OK")
            serial_read_login(debug_serial, 1, debug_log)
            continue
        elif "~#" in result:
            write_log("登录成功", debug_log)
            # at_write("echo 2 >/proc/sys/kernel/printk\r\n", 3, debug_serial, "OK")
            serial_read_login(debug_serial, 1, debug_log)
            break
        elif '/ #' in result:
            write_log("登录成功", debug_log)
            # at_write("echo 2 >/proc/sys/kernel/printk\r\n", 3, debug_serial, "OK")
            serial_read_login(debug_serial, 1, debug_log)
            break
        elif '/data #' in result:
            write_log("登录成功", debug_log)
            # at_write("echo 2 >/proc/sys/kernel/printk\r\n", 3, debug_serial, "OK")
            serial_read_login(debug_serial, 1, debug_log)
            break
        elif 'Login incorrect' in result:
            write_log("登录密码不对,重新登录", debug_log)
            # at_write("echo 2 >/proc/sys/kernel/printk\r\n", 3, debug_serial, "OK")
            serial_read_login(debug_serial, 1, debug_log)
            continue
        else:
            # write_log("登录成功", debug_log)
            # at_write("echo 2 >/proc/sys/kernel/printk\r\n", 3, debug_serial, "OK")
            # serial_read(debug_serial, 1, debug_log)
            # break
            # debug_serial.write(chr(0x03).encode())
            continue
def loginDevice_1():
    global DEBUG_LOG
    # 确认登录失败的条件，或者，不可能失败
    while True:
        print("等待登录... ... ")
        time.sleep(3)
        at_write("\r\n", 3, debug_serial, "OK")
        time.sleep(1)
        result = at_read(debug_serial, DEBUG_LOG)
        # with open(DEBUG_LOG, 'a') as file_object:
            # file_object.write(result)
        if "login:" in result:
            at_write("root\r\n", 3, debug_serial, "OK")
            print("账号输入成功")
            time.sleep(2)
            at_write("oelinux123\r\n", 3, debug_serial, "OK")
            print("密码输入成功")
        elif "~ #" in result:
            write_log("登录成功", DEBUG_LOG)
            at_write("rm -rf /usrdata/qsee.log", 3, debug_serial, "OK")
            at_write("rm -rf /usrdata/tz.log", 3, debug_serial, "OK")
            at_write("lcat /proc/tzdbg/qsee_log > /usrdata/qsee.log &\r\n", 3, debug_serial, "OK")
            at_write("cat /proc/tzdbg/log > /usrdata/tz.log &\r\n", 3, debug_serial, "OK")
            at_write("echo 2 >/proc/sys/kernel/printk\r\n", 3, debug_serial, "OK")
            at_read(debug_serial, DEBUG_LOG)
            break
        elif '/ #' in result:
            write_log("登录成功",DEBUG_LOG)
            at_write("echo 2 >/proc/sys/kernel/printk\r\n", 3, debug_serial, "OK")
            at_read(debug_serial, DEBUG_LOG)
            break
        else:
            write_log("登录成功", DEBUG_LOG)
            break

#log写入函数
def write_log(log,logFile=""):
    with open(logFile, 'a') as file_object:
        file_object.write(str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "\r\n" + log+ "\r\n")
        print(log)

def into_gnss_app():
    at_write("cd /data\r\n", 3, debug_serial, "OK")
    # at_write("logcat -f /tmp/logcat.txt &\r\n", 3, debug_serial, "OK")
    # at_write("logcat -f /usrdata/logcat.txt &", 3, debug_serial, "OK")
    # time.sleep(1)
    # at_write("dmesg > /usrdata/dmesg.txt &", 3, debug_serial, "OK")
    # time.sleep(1)
    # at_write("echo 2 >/proc/sys/kernel/printk\r\n", 3, debug_serial, "OK")
    # time.sleep(1)
    at_write("ql_sdk_api_test\r\n", 3, debug_serial, "OK")
    time.sleep(1)
    at_write("12\n0\n1\n1\n1\n", 3, debug_serial, "OK")
    at_read(debug_serial, DEBUG_LOG)
    # with open(DEBUG_LOG, 'a') as file_object:
        # file_object.write(str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) +"\r\n"+str(recv_value))
    at_write("5\n1000\n0\n", 3, debug_serial, "OK")         #//这行的“5”为启动gnss的接口序号，如果接口顺序变了，改这里即可
    time.sleep(1)
    write_log(str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))+":开始进行GNSS测试，期望2分钟内定位成功，检查第二分钟内定位语句格式正确，请稍等",DEBUG_LOG)
    

def check_modem():
    for i in range(60):
        at_write("cat /sys/class/remoteproc/remoteproc0/state\r\n", 3, debug_serial, "OK")
        time.sleep(1)
        at_write("cat /sys/class/remoteproc/remoteproc0/crash_count\r\n", 3, debug_serial, "OK")
        result = at_read(debug_serial, DEBUG_LOG)
        if "running" not in result:
            print("modem 状态检查异常")
            sys.exit()
        elif i == 59:
            print("modem 状态检查正常")
def start_gnss():
    global not_gnss_fail_count
    # not_match_fail_count=0
    not_gnss_fail_count=0
    at_write("gnss --start\r\n", 3, debug_serial, "OK")
    # time.sleep(60)
    for i in range(150):
        result = at_read(debug_serial, DEBUG_LOG)
        if '$GNRMC' in result:
            # debug_serial.write(chr(0x03).encode())
            # init_value = at_read(debug_serial, DEBUG_LOG)
            break
        elif i == 149:
            not_gnss_fail_count += 1
            sys.exit()
            # debug_serial.write(chr(0x03).encode())
            # init_value = at_read(debug_serial, DEBUG_LOG)
    
def check_gnss():
    for i in range(60):
        time.sleep(1)
        print('****************')
        at_read(debug_serial, DEBUG_LOG)
    for j in range(120):
        result = at_read(debug_serial, DEBUG_LOG)
        if '$GNRMC' in result:
            debug_serial.write(chr(0x03).encode())
            init_value = at_read(debug_serial, DEBUG_LOG)
            break
        elif j == 119:
            not_gnss_fail_count += 1
            debug_serial.write(chr(0x03).encode())
            init_value = at_read(debug_serial, DEBUG_LOG)
            at_write("ql_cmd at at+qtest=\"dump\",1\r\n", 3, debug_serial, "OK")
            time.sleep(30)
            at_read(debug_serial, DEBUG_LOG)
            at_read(debug_serial, DEBUG_LOG)
            at_read(debug_serial, DEBUG_LOG)
            at_read(debug_serial, DEBUG_LOG)
            sys.exit()
def getNmeaLog():
    start_time = time.time()
    suc_state = False
    extra_nmea_list = []
    nmea_list = []
    global pass_count,not_match_fail_count,not_gnss_fail_count
    pass_count=0
    not_match_fail_count=0
    not_gnss_fail_count=0
    while True:
        nmea_value_tmp = at_readline(debug_serial)
        nmea_value = str(nmea_value_tmp)[1:].replace("Please enter your choice: ","").replace("\\r\\r\\n", '').replace("'", '')
        end_time = time.time()
        gnss_loc = len(re.findall(RMC_Sta[0], str(nmea_value)))
        #result_list = re.findall(RMC_Sta[0], str(nmea_value))
        #print(result_list)
        #gnss_loc = len(result_list)
        
        runtime = end_time - start_time
        with open(DEBUG_LOG, 'a') as file_object:
            file_object.write(str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + ":" + str(nmea_value) +"\r\n")
        if runtime < 60 and gnss_loc != 0:
            suc_time = runtime
            suc_state = True
            write_log(str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))+":定位成功,定位时间:%s 秒" % suc_time, DEBUG_LOG)
            write_log(str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + ":开始截取第二分钟内{}秒GNSS log,请稍等".format(str(check_log_time)),DEBUG_LOG)
            break
        elif runtime >= 60:
            write_log(str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))+"：超出未定位成功", DEBUG_LOG)
            not_gnss_fail_count += 1
            # sys.exit()
            # debug_serial.write(chr(0x03).encode())
            # time.sleep(1)
            # debug_serial.write(chr(0x03).encode())
            # time.sleep(1)
            # at_write("logcat -f /usrdata/logcat.txt &\r\n", 3, debug_serial, "OK")
            # time.sleep(1)
            # at_read(debug_serial, DEBUG_LOG)
            # at_write("dmesg > /usrdata/dmesg.txt &\r\n", 3, debug_serial, "OK")
            # time.sleep(1)
        elif runtime >= 180:
            break
    #过滤2minlog
    print("############1111111")
    start_time = time.time()
    while True:
        nmea_value_tmp = at_readline(debug_serial)
        end_time = time.time()
        runtime = end_time - start_time
        if runtime >= 120:
            break
        
    t0_time = time.time()

    if suc_state:
        while True:
            nmea_value_tmp = at_readline(debug_serial)
            nmea_value = str(nmea_value_tmp)[1:].replace("Please enter your choice: ","").replace("\\r\\r\\n", '').replace("'", '')
            # print("nmea_value", nmea_value)
            if not any(w in nmea_value and w for w in nmea_type):
                    extra_nmea_list.append("FAIL:期望无该类型语句，实际有"+str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + ":" +nmea_value)
                    print("111111111111111111111111111111111")
            with open(DEBUG_LOG, 'a') as file_object:
                file_object.write(str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + ":" + str(nmea_value) +"\r\n")
                t1_time = time.time()
                log_time = t1_time - t0_time
                time_result = str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + ":" + nmea_value
                if log_time < check_log_time:
                    nmea_list.append(time_result)
                else:
                    break
    for tmp in nmea_list:
        for key, value in check_list.items():
            if key in tmp:
                value.append(tmp.replace("\r", "").replace("\n", ""))
                print("############2222222")
    # print("nmea_list",nmea_list)
    # 句式匹配
    # print(check_list)
    match_sate = True
    match_suc_list = []
    no_nmea_list = []
    match_pass_type_list = []
    for key, value in check_list.items():
        # print("key\t",key)
        # print("value[0]\t",value[0])
        if len(value) == 1:
            info_value = "FAIL:" + key + ":GNSS语句中期望有该类型语句,实际无"
            no_nmea_list.append(info_value)
            print("############3333333")
        k = 0
        for i in range(1, len(value)):
            for j in range(len(value[0])):
                if len(value[0][j].split(",")) == len(value[i].split(",")):
                    # print(value[0][j]+"\t"+value[i]+"\t长度匹配OK")
                    matchObj = re.match(value[0][j], value[i].split(":")[-1], re.M | re.I)
                    print("############4444444")
                    if matchObj:
                        # print(value[1][j]+"\t"+value[i]+"\t格式匹配OK")
                        match_suc_list.append(value[i])
                        k += 1
                        print("############5555555")
                        if k == len(value) - 1:
                            match_pass_type = "PASS:" + key + "句式符合"
                            match_pass_type_list.append(match_pass_type)
                            print("############666666")
        match_fail_list = list(set(value[1:]).difference(set(match_suc_list)))

        if len(match_fail_list) > 0:
            match_sate = False
            for fail_sent in match_fail_list:
                tmp = 'FAIL：' + key + ":" + fail_sent.replace("\r", "").replace("\n", "") + ":与任意格式均不匹配"
                write_log(tmp, DEBUG_LOG)
                print("############7777777")
    if len(no_nmea_list)> 0:
        match_sate = False
        for fail_sent in list(set(no_nmea_list)):
            write_log(fail_sent, DEBUG_LOG)
            print("############88888888888")
    match_pass_type_list_union = list(set(match_pass_type_list))
    if len(match_pass_type_list_union) > 0:
        for pass_type in match_pass_type_list_union:
            write_log(pass_type, DEBUG_LOG)
            print("############999999999")
    if len(extra_nmea_list) > 0:
        match_sate = False
        for fail_sent in extra_nmea_list:
            write_log(fail_sent, DEBUG_LOG)
            print("############10101010")
    if not match_sate:
        not_match_fail_count += 1
        print("存在格式不匹配项，整个用例FAIL")
        # debug_serial.write(chr(0x03).encode())
        # time.sleep(1)
        # debug_serial.write(chr(0x03).encode())
        # time.sleep(1)
        # at_write("logcat -f /usrdata/logcat.txt &\r\n", 3, debug_serial, "OK")
        # time.sleep(1)
        # at_read(debug_serial, DEBUG_LOG)
        at_write("dmesg > /usrdata/dmesg.txt &\r\n", 3, debug_serial, "OK")
        time.sleep(3)
        at_write("ql_cmd sysinfo /tmp/\r\n", 3, debug_serial, "OK")
        time.sleep(3)
        # sys.exit()
    else:
        pass_count += 1
        print("不存在格式不匹配项，passed!!!")

def sys_reboot():
    #重启
    global reboot_fail
    reboot_fail=0
    at_write("reboot\r\n", 3, debug_serial, "OK")
    # time.sleep(60)
    i = 0
    reboot_res = 1
    while True:
        res1 = at_read(debug_serial, DEBUG_LOG)
        if 'Format:' in res1:
            pass
        if 'login:' in res1:
            break
        i += 1
        if i > 100:
            # print("重启失败，failed!!!\r\n")
            reboot_res == 0
            break
    if reboot_res == 0:
        # print("重启失败，failed!!!")
        reboot_fail+= 1
    else:
        print("重启成功")
# def IntoAdbShell(adbID):
	# process1 = subprocess.Popen("adb -s {} root".format(adbID), shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
								   # stderr=subprocess.PIPE, encoding="utf-8")
	# return process1
def IntoAdbShell_1(adbID):
	process = subprocess.Popen("adb -s {} shell".format(adbID), shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
								   stderr=subprocess.PIPE, encoding="utf-8")
	return process

def AdbShellCommand(process, cmd, excptRes, timeout):
	info = ''
	process.stdin.write(cmd)
	process.stdin.flush()
	while True:
		info_tmp = process.stdout.readline(1024)
		info = '{}{}'.format(info, info_tmp).replace("\n\n","\n")
		if excptRes is None:
			return info
		if excptRes in info:
			print('rev: {}.'.format(info))
			# print('excptRes is in rev.')
			with open(ADB_LOG, 'a+') as file_object:
				file_object.write("[" + str(datetime.datetime.now()) + "] " + info)
			return info
		else:
			if not info:
				break

if __name__ == "__main__":
    runtimes = 0
    check_port_status()
    debug_serial.write(chr(0x03).encode())
    creatLogFile()
    # IntoAdbShell(DevicesID)
    loginDevice(debug_serial, DEBUG_LOG)
    while True:
        runtimes += 1
        loginDevice(debug_serial, DEBUG_LOG)
        time.sleep(1)
        check_mssr()
        # os.popen("adb -s {} root".format(DevicesID))
        # time.sleep(5)
        # process3 = IntoAdbShell_1(DevicesID)
        # print("1111111111111")
        # AdbShellCommand(process3, 'ls /usrdata/\r\n', '*', 1)
        # time.sleep(1)
        # AdbShellCommand(process3, 'dmesg >/usrdata/dmesg.txt &\r', '*', 1)
        # time.sleep(1)
        # AdbShellCommand(process3, 'ls\r', '#', 1)
        # check_modem()
        # into_gnss_app()
        flushInput()
        # getNmeaLog()
        start_gnss()
        check_gnss()
        debug_serial.write(chr(0x03).encode())
        init_value = at_read(debug_serial, DEBUG_LOG)
        time.sleep(1)
        debug_serial.write(chr(0x1A).encode())
        init_value = at_read(debug_serial, DEBUG_LOG)
        at_write("\r\n", 3, debug_serial, "OK")
        sys_reboot()
        # time.sleep(10)
        write_log(
            "**********{}:运行次数{}**********重启失败次数{}**********定位失败次数{}".format(
                str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())), str(runtimes),str(reboot_fail),str(not_gnss_fail_count)),
            DEBUG_LOG)
        with open(DEBUG_LOG, 'a') as file_object:
            file_object.write(
                "**********{}:runtimes{}**********reboot fail count{}**********gnss fail count{}".format(
                    str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())), str(runtimes), str(reboot_fail),
                    str(not_gnss_fail_count)))